<template>
  <v-navigation-drawer
    v-model="userDrawer"
    location="left"
    className="w-full"
    :width="config.screenWidth"
  >
    <v-list-item
      :prepend-avatar="userInfo.getHeader()"
      :title="userInfo.user.username"
      nav
    >
      <template v-slot:append>
        <v-icon :icon="mdiChevronLeft" size="50" @click.stop="closeCallback" />
      </template>
    </v-list-item>

    <v-divider></v-divider>
    <v-list nav>
      <v-list-item
        v-for="(i, index) in opeList"
        :title="i.title"
        :key="index"
        @click="toOpe(i)"
      />
    </v-list>

    <!-- 修改个人信息 -->
    <v-navigation-drawer
      v-model="editUser"
      location="left"
      temporary
      :width="config.screenWidth"
    >
      <div className="m-1 flex justify-between items-center">
        <div className="px-3">修改个人信息</div>
        <v-icon :icon="mdiChevronLeft" size="50" @click="editUser = false" />
      </div>
      <!-- 头像 -->
      <div className="flex justify-center">
        <v-badge color="info" content="点击头像更换">
          <v-avatar
            :image="userInfo.getHeader()"
            size="80"
            @click="editHeader = true"
          />
        </v-badge>
      </div>
      <div class="p-5 bg-white rounded-md">
        <v-sheet class="mx-auto">
          <v-form fast-fail @submit.prevent="toUpdateInfo">
            <v-text-field
              v-model="form.username"
              :rules="[valRequired('用户名')]"
              label="用户名"
            ></v-text-field>
            <v-select
              v-model="form.sex"
              :items="[
                { name: '男', val: '1' },
                { name: '女', val: '2' },
              ]"
              item-title="name"
              item-value="val"
              label="性别"
              required
            />
            <v-btn class="mt-2" type="submit" block>更新</v-btn>
            <v-btn class="mt-2" block @click="editPassword = true"
              >修改密码</v-btn
            >
          </v-form>
        </v-sheet>
      </div>
      <!-- 更换头像 -->
      <v-navigation-drawer
        v-model="editHeader"
        location="left"
        temporary
        :width="config.screenWidth"
      >
        <div className="m-1 flex justify-between items-center">
          <div className="px-3">更换头像</div>
          <v-icon
            :icon="mdiChevronLeft"
            size="50"
            @click="editHeader = false"
          />
        </div>
        <v-toolbar color="surface">
          <v-tabs v-model="tabs" color="primary" grow>
            <v-tab :value="1">
              <v-icon :icon="mdiGenderMale"></v-icon>
            </v-tab>
            <v-tab :value="2">
              <v-icon :icon="mdiGenderFemale" color="pink"></v-icon>
            </v-tab>
          </v-tabs>
        </v-toolbar>
        <v-tabs-window v-model="tabs">
          <v-tabs-window-item :key="1" :value="1">
            <div className="grid grid-cols-4 gap-4 gap-x-4 gap-y-4 p-3">
              <div
                v-for="i in manList"
                :key="i"
                :className="
                  curHeader === i
                    ? 'border-2 border-blue-500 rounded-md p-2'
                    : 'p-2'
                "
                @click="curHeader = i"
              >
                <img :src="userInfo.getHeader(i)" alt="" />
              </div>
            </div>
          </v-tabs-window-item>
          <v-tabs-window-item :key="2" :value="2">
            <div className="grid grid-cols-4 gap-4 gap-x-4 gap-y-4 p-3">
              <div
                v-for="i in womanList"
                :key="i"
                :className="
                  curHeader === i
                    ? 'border-2 border-pink-500 rounded-md p-2'
                    : 'p-2'
                "
                @click="curHeader = i"
              >
                <img :src="userInfo.getHeader(i)" alt="" />
              </div></div
          ></v-tabs-window-item>
        </v-tabs-window>
        <div className="w-full px-2">
          <v-btn block @click="changeHeader">确认</v-btn>
        </div>
      </v-navigation-drawer>
      <!-- 更换头像 -->
      <!-- 修改密码 -->
      <v-navigation-drawer
        v-model="editPassword"
        location="left"
        temporary
        :width="config.screenWidth"
      >
        <div className="m-1 flex justify-between items-center">
          <div className="px-3">修改密码</div>
          <v-icon
            :icon="mdiChevronLeft"
            size="50"
            @click="editPassword = false"
          />
        </div>
        <div class="p-5 bg-white rounded-md">
          <v-sheet class="mx-auto">
            <v-form fast-fail @submit.prevent="toUpdatePassword">
              <v-text-field
                v-model="passwordForm.password"
                :rules="[valRequired('旧密码')]"
                label="旧密码"
              />
              <v-text-field
                v-model="passwordForm.newPassword"
                :rules="[valRequired('新密码'), valPassword]"
                label="新密码"
              />
              <v-text-field
                v-model="passwordForm.newPasswordConfirm"
                :rules="[valRequired('确认新密码'), valConfirmPassword]"
                label="确认新密码"
              />
              <v-btn class="mt-2" type="submit" block>确认</v-btn>
            </v-form>
          </v-sheet>
        </div>

        <v-dialog v-model="dialog" width="auto">
          <v-card
            max-width="400"
            text="确认要修改密码吗？修改成功后需要重新登录！"
            title="确认修改密码"
          >
            <template v-slot:actions>
              <v-btn color="black" text="不了" @click="dialog = false" />
              <v-btn color="info" text="确认" @click="sendUpdatePassword" />
            </template>
          </v-card>
        </v-dialog>
      </v-navigation-drawer>
    </v-navigation-drawer>
  </v-navigation-drawer>
</template>
<script lang="ts" setup>
import { updateAvatar, updatePassword, updateUser } from "@/api";
import { useConfig } from "@/store/localConfig";
import { useUserInfoStore } from "@/store/userInfo";
import { uMsg } from "@/store/vMessage";
import { mdiChevronLeft, mdiGenderFemale, mdiGenderMale } from "@mdi/js";
import { ref } from "vue";
import { useRouter } from "vue-router";

const emit = defineEmits(["close"]);
const userInfo = useUserInfoStore();
const config = useConfig();
const userDrawer = ref<boolean>(false);
const editUser = ref<boolean>(false);
const editPassword = ref<boolean>(false);
const vMsg = uMsg();
const dialog = ref<boolean>(false);
const editHeader = ref<boolean>(false);
const tabs = ref<number>(1);
const curHeader = ref<string>(userInfo.user.avatar);
const router = useRouter()

const opeList = [
  {
    title: "修改个人信息",
    value: 0,
  },
  {
    title: "退出",
    value: 1,
  },
];

const closeCallback = () => {
  userDrawer.value = false;
  emit("close");
};

const toOpe = (item: { value: number }) => {
  switch (item.value) {
    case 0:
      // 修改
      editUser.value = true;
      form.value.username = userInfo.user.username;
      form.value.sex = userInfo.user.sex.toString();
      break;
    case 1:
      // 注销
      userInfo.toLogout();
      break;
  }
};

let manList: string[] = [];
let womanList: string[] = [];
// 头像
for (let i = 1; i < 41; i++) {
  if (i < 21) {
    if (i < 10) manList.push("0" + i.toString());
    else manList.push(i.toString());
  } else {
    womanList.push(i.toString());
  }
}

// 修改头像
const changeHeader = () => {
  updateAvatar(userInfo.user.id, curHeader.value).then(() => {
    userInfo.user.avatar = curHeader.value;
  });
};

// 修改个人信息
const form = ref({
  id: userInfo.user.id.toString(),
  username: "",
  sex: "1",
});

// 修改密码
const passwordForm = ref({
  id: userInfo.user.id.toString(),
  password: "",
  newPassword: "",
  newPasswordConfirm: "",
});

// 修改个人信息
const toUpdateInfo = async (event: Promise<{ valid: boolean }>) => {
  // 异步校验
  let validate = await event;
  // 发起注册请求
  validate.valid &&
    updateUser(form.value).then(() => {
      // 更新用户信息
      userInfo.user.username = form.value.username;
      userInfo.getUserInfo();
    });
};

// 修改密码
const toUpdatePassword = async (event: Promise<{ valid: boolean }>) => {
  // 异步校验
  let validate = await event;
  validate.valid && (dialog.value = true);
};

const sendUpdatePassword = () => {
  dialog.value = false;
  updatePassword(passwordForm.value).then(() => {
    // 跳转回登录页面重新登录
    vMsg.Open("密码修改成功！请使用新密码重新登录");
    // 注销登录
    userInfo.toLogout();
    router.push({ path: "/" });
    // 关闭弹框
    userDrawer.value = false;
    editUser.value = false;
    editPassword.value = false;
  });
};

// 校验规则：必填
const valRequired = (key: string) => (v: string) => !!v || `${key}必填！`;

const valConfirmPassword = () =>
  passwordForm.value.newPassword === passwordForm.value.newPasswordConfirm
    ? true
    : "两次密码不一致";

const valPassword = () =>
  passwordForm.value.password !== passwordForm.value.newPassword
    ? true
    : "新旧密码不能相同";

defineExpose({
  userDrawer,
});
</script>
